package com.example.minademo.service.impl;

import com.example.minademo.dao.ControllerDao;
import com.example.minademo.dao.UserDao;
import com.example.minademo.entity.Controller;
import com.example.minademo.entity.User;
import com.example.minademo.service.ControllerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ControllerServiceImpl implements ControllerService {

    @Autowired
    private ControllerDao mControllerDao;

    @Autowired
    private UserDao mUserDao;
    @Override
    public List<User> findControlledUsersByUserId(Integer userId) {
        List<User> users = new ArrayList<>();
        List<Controller> controllers = mControllerDao.findAllByUserId(userId);
        if(controllers != null) {
            List<Integer> ids = new ArrayList<>();
            for (Controller controller : controllers) {
                ids.add(controller.getControlledUserId());
            }
            users = mUserDao.findAllById(ids);
        }
        return users;

    }

    @Override
    public Controller save(Integer userId, Integer controlledUserId, String controlledUserName) {
        Controller controller = new Controller();
        controller.setUserId(userId);
        controller.setControlledUserId(controlledUserId);
        controller.setControlledUserName(controlledUserName);
        return mControllerDao.save(controller);
    }

    @Override
    public Controller updateShotNumber(Integer userId, Integer controlledUserId) {

        Controller controller = mControllerDao.findByUserIdAndControlledUserId(userId,controlledUserId);
        Integer number = controller.getShotNumber();
        controller.setShotNumber(number == null ? 1 : number + 1);
        return controller;
    }

    @Override
    public Controller findByUserIdAndControlledUserId(Integer userId, Integer controlledUserId) {
        return mControllerDao.findByUserIdAndControlledUserId(userId,controlledUserId);
    }

}
